const express = require('express')
const router = express.Router()
const connection = require('../db/sql')
let jwt = require('jsonwebtoken')

function getTimeToken(exp) {
  const getTime = parseInt(new Date().getTime() / 1000)
  return getTime - exp > 60 * 3600
}

/**
 * 添加购物车数据
 */
router.post('/addCart', (req, res) => {
  const goodsId = req.body.goodsId
  const token = req.headers.token
  const tokenObj = jwt.decode(token)

  //如果执行，就证明token过期了
  if (getTimeToken(tokenObj.exp)) {
    res.send({
      data: {
        code: 1000
      }
    })
  }

  //查询用户
  connection.query(`select * from user where tel = ${tokenObj.tel}`, (error, results) => {
    //用户id
    const uId = results[0].id;
    //查询商品
    connection.query(`select * from goods_list where id=${goodsId}`, (err, result) => {
      const goodsName = result[0].name;
      const goodsPrice = result[0].price;
      const goodsImgUrl = result[0].imgUrl;
      //查询当前用户在之前是否添加过本商品
      connection.query(`select * from goods_cart where uId=${uId} and goods_id=${goodsId}`, (e, r) => {
        //用户之前是添加过商品到购物车
        if (r.length > 0) {
          let num = r[0].goods_num;
          connection.query(`update goods_cart set goods_num = replace(goods_num,${num},${parseInt(num) + 1}) where id = ${r[0].id}`, (e, datas) => {
            res.send({
              data: {
                code: 200,
                success: true,
                msg: '添加成功'
              }
            })
          })
        } else {
          //没有
          connection.query(`insert into goods_cart (uId,goods_id,goods_name,goods_price,goods_num,goods_imgUrl) values ("${uId}","${goodsId}","${goodsName}","${goodsPrice}","1","${goodsImgUrl}")`, () => {
            res.send({
              data: {
                code: 200,
                success: true,
                msg: '添加成功'
              }
            })
          })
        }
      })
    })
  })
})

/**
 * 删除购物车数据
 */
router.post('/deleteCart', (req, res) => {

  const arrId = req.body.arrId

  for (let i = 0; i < arrId.length; i++) {
    connection.query(`delete from goods_cart where id = ${arrId[i]}`, (error, results) => {
      res.send({
        data: {
          code: 200,
          success: true,
          msg: '删除成功'
        }
      })
    })
  }
})


/**
 * 修改购物车数量
 */
router.post('/updateNum', (req, res) => {

  const id = req.body.id;
  const changeNum = req.body.num;

  connection.query(`select * from goods_cart where id = ${id}`, (error, results) => {
    //原来的数量
    const num = results[0].goods_num;
    connection.query(`update goods_cart set goods_num = replace(goods_num,${num},${changeNum}) where id = ${id}`, (err, result) => {
      res.send({
        data: {
          code: 200,
          success: true
        }
      })
    })
  })
})

/**
 * 查询购物车数据
 */
router.post('/selectCart', (req, res) => {
  //token
  const token = req.headers.token;
  const tokenObj = jwt.decode(token);
  //查询用户
  connection.query(`select * from user where tel = ${tokenObj.tel}`, (error, results) => {
    //用户id
    const uId = results[0].id;
    //查询购物车
    connection.query(`select * from goods_cart where uId = ${uId}`, (err, result) => {
      res.send({
        data: {
          code: 200,
          success: true,
          data: result
        }
      })
    })
  })
})

module.exports = router